from lib import common
from conf import setting
from db import db_handler

#1.商家功能接口

#1.1查看商品列表
def check_goods_interface(addr):
    goods_list=common.return_list(addr)
    if len(goods_list)<=0:
        return False,'商品列表为空，请添加商品后查看...'
    else:
        return True,goods_list


#1.2增加商品
def add_goods_interface(name,price,count=100,addr=setting.GOODS_PATH):
    goods_dic=db_handler.select(name,addr)
    if goods_dic:
        return False,'商品:%s 已存在，请进入选择其他功能进行操作!'%name
    else:
        goods_dic={'name':name,'price':price,'count':count}
        db_handler.save(goods_dic,addr)
        return True,'添加商品:%s 成功!'%name


#1.3下架商品
def remove_goods_interface(name,addr=setting.GOODS_PATH):
    flag=db_handler.delete(name,addr)
    if flag:
        return True,'下架商品:%s 成功!'%name
    else:
        return False,'下架失败,商品:%s 不存在!'%name

#1.4更新商品价格和商品的库存
def update_goods_interface(name,price,count,addr=setting.GOODS_PATH):
    goods_dic=db_handler.select(name,addr)
    if goods_dic:
        goods_dic['price']=price
        goods_dic['count']=count
        db_handler.save(goods_dic,addr)

        return True,'更新商品:%s 成功!'%name
    else:
        return False,'您输入的商品:%s 不存在!'





#2.用户入口
#2.1结账离开打印消费
def  consumer_list(consumer_name,addr=setting.GOODS_PATH):
    consumer_dic=db_handler.select(consumer_name)
    if len(consumer_dic['shoppingcar'])>0:
        return  True,'退出购物，您目前余额为:%s,' % (consumer_dic['balance'])

    else:
        return False,'用户:%s 尚未购买任何商品.'%consumer_name




#2.2用户购买商品接口
def buy_goods_interface(consumer_name,goods_name,consumer_addr=setting.USER_PATH,goods_addr=setting.GOODS_PATH):
    consumer_dic=db_handler.select(consumer_name,consumer_addr)
    goods_dic=db_handler.select(goods_name,goods_addr)

    if consumer_dic['balance']>=goods_dic['price']:
        if goods_dic['count']>=0:
            if goods_name in consumer_dic['shoppingcar']:#若在购物车，则数量+1
                consumer_dic['shoppingcar'][goods_name]+=1
            else:
                consumer_dic['shoppingcar'][goods_name] = 1#若第一次购买，则熟练=1
            consumer_dic['balance']-=goods_dic['price']
            goods_dic['count']-=1

            db_handler.save(goods_dic,goods_addr)
            db_handler.save(consumer_dic,consumer_addr)

            return True,'购买商品:%s 成功！'%goods_name
        else:
            return False,'商品:%s 库存不足，购买失败！'%goods_dic['count']
    else:
        return False,'您的余额为:%s 不足购买，请选择其他商品..'%consumer_dic['balance']




#2.3查看用户的购物车
def check_shoppingcar(username,addr=setting.USER_PATH):
    user_dic=db_handler.select(username,addr)
    if len(user_dic['shoppingcar'])==0:
        return False,'购物车空空如也...'
    else:
        return True,user_dic['shoppingcar']



